package com.h3c.nem.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.DateUtils;
import com.eos.common.util.IdWorker;
import com.eos.common.util.Result;
import com.eos.common.util.UserUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.async.AsyncSendMessage;
import com.h3c.nem.client.DataCenterFeignClient;
import com.h3c.nem.client.EosSyncDataClient;
import com.h3c.nem.config.SpringUtil;
import com.h3c.nem.dto.*;
import com.h3c.nem.entity.*;
import com.h3c.nem.enums.AutoOpTypeEnum;
import com.h3c.nem.enums.CertifiedStatusEnum;
import com.h3c.nem.mapper.*;
import com.h3c.nem.service.*;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.BusiEnumDefine;
import com.h3c.nem.utils.CommonUtil;
import com.h3c.nem.utils.InitExampleOrderByUtils;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: TbTeacherServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-01-19
 * Description: tb_teacher serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class TbTeacherServiceImpl extends ServiceImpl<TbTeacherMapper, TbTeacher> implements ITbTeacherService {

    @Resource
    private TbTeacherMapper tbTeacherMapper;

    @Resource
    private ISdAllWorkerService sdAllWorkerService;
    @Autowired
    CommService commService;

    @Autowired
    DataCenterFeignClient dataCenterFeignClient;

    @Resource
    private AsyncSendMessage asyncSendMessage;

    @Resource
    private ISdNoticeRecordService iSdNoticeRecordService;

    @Autowired
    SdDeptMapper sdDeptMapper;

    @Resource
    private ISdEmailTemplateService emailTemplateService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    TbWorkerMapper tbWorkerMapper;

    @Autowired
    private SdAllWorkerMapper sdAllWorkerMapper;

    @Autowired
    private SdUserMapper sdUserMapper;

    @Autowired
    private TbTeacherCertificationInfoMapper tbTeacherCertificationInfoMapper;

    @Autowired
    private TbApprovalRecordMapper tbApprovalRecordMapper;

    @Resource
    private ITbApprovalRecordService approvalRecordService;
    @Resource
    private ISdNoticeRecordService noticeRecordService;

    @Resource
    private EosSyncDataClient eosSyncDataClient;
    @Resource
    private UserUtils userUtils;
    @Autowired
    private TbTeachScheduleMapper teachScheduleMapper;

    @Autowired
    private ISdDeptService deptService;
    @Autowired
    private AsyncSendMessage sendMessage;

    @Value("${teacher.certification.course.id}")
    private String courseId;
    @Value("${eos.nem.account}")
    private String eosNemAccount;
    @Value("${eos.nem.password}")
    private String eosNemPassword;

    private static final String deptRedis = "nem_dept_";

    @Value("${teacher-allowance}")
    private Integer allowanceMoney;
    @Value("${dajiangtang.email}")
    private String dajiangtangEmail;


    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-02-08
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public List<TbTeacherDTO> selectFuzzyByDto(TbTeacherDTO dto) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //List<TbTeacher> list = tbTeacherMapper.selectByExample(initFuzzyExample(dto));
        List<String> teacherIdList = null;
        if (!StringUtils.isEmpty(dto.getTeacherId())) {
            teacherIdList = Arrays.asList(dto.getTeacherId().split(","));
        }
        List<String> deptIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(dto.getDeptId())) {
            deptIdList.addAll( Arrays.asList(dto.getDeptId().split(",")));
        }
        if(deptIdList.size()==0){
            return new ArrayList<TbTeacherDTO>();
        }
        List<Integer> deptIds = new ArrayList<>();
        for (String s : deptIdList) {
            deptIds.add(Integer.valueOf(s));
        }
        List<TbTeacher> list = tbTeacherMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto), TbTeacher.class),deptIds , teacherIdList);
/*        List<TbTeacher> list = tbTeacherMapper.selectList(new QueryWrapper<TbTeacher>()
                .in(teacherIdList.size()>0,"teacher_id",teacherIdList)
                .in("direct_dept_id",deptIdIdList)
        );*/


        List<TbTeacherDTO> tbTeacherDTOS = JSONArray.parseArray(JSONArray.toJSONString(list), TbTeacherDTO.class);

        List<TbApprovalRecord> tbApprovalRecords = tbApprovalRecordMapper.selectList(new QueryWrapper<TbApprovalRecord>()
                .eq("approval_type",BusiEnumDefine.TEACHER_CERTIFICATION_APPROVAL)
        );
        Map<String,List<TbApprovalRecord>> approvalMap = tbApprovalRecords.stream().collect(
                Collectors.groupingBy(TbApprovalRecord::getFlowId));


        for (TbTeacherDTO tbTeacherDTO : tbTeacherDTOS) {
            try{
                log.info(tbTeacherDTO.getTeacherId()+"--------------------------");
                if(tbTeacherDTO.getCertifiedTime()!=null){
                    tbTeacherDTO.setCertifiedTimeStr(sdf.format(tbTeacherDTO.getCertifiedTime()));
                }

            }catch (Exception e){
                e.printStackTrace();
            }

            List<TbApprovalRecord> tbApprovalRecordList = approvalMap.get(tbTeacherDTO.getTeacherId());
            if(!CollectionUtils.isEmpty(tbApprovalRecordList)){
                StringBuilder stringBuilder = new StringBuilder();
                for (TbApprovalRecord approvalRecord : tbApprovalRecordList) {
                    String time = sdf.format(approvalRecord.getApprovalTime());
                    stringBuilder
                            .append("(")
                            .append(time)
                            .append(" ")
                            .append(approvalRecord.getApprovalScore())
                            .append("分)")
                            .append(" ");
                    tbTeacherDTO.setCheckRecord(stringBuilder.toString());
                }
            }
            List<TbWorker> tbWorkerListOne = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>()
                    .like("teacher_info", tbTeacherDTO.getTeacherId())
                    .in("worker_status", 1, 2));
            List<TbWorker> tbWorkerListTwo = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>()
                    .like("teacher_info", tbTeacherDTO.getTeacherId())
                    .in("worker_status", 3));

            if (!tbWorkerListOne.isEmpty() || !tbWorkerListTwo.isEmpty()) {
                tbTeacherDTO.setHelpNum(tbWorkerListTwo.size() + "/" + tbWorkerListOne.size());
            }
            int judgeFlag = 0;
            if (!StringUtils.isEmpty(tbTeacherDTO.getLast4kpi())) {
                String[] arr = tbTeacherDTO.getLast4kpi().split(";");

                for (int i = 3; i >= 0; i--) {
                    if (arr.length > i) {
                        if (i == 3) {
                            tbTeacherDTO.setLastKpi4(arr[i].split(":")[1]);
                        } else if (i == 2) {
                            tbTeacherDTO.setLastKpi3(arr[i].split(":")[1]);
                        } else if (i == 1) {
                            tbTeacherDTO.setLastKpi2(arr[i].split(":")[1]);
                        } else {
                            tbTeacherDTO.setLastKpi1(arr[i].split(":")[1]);
                        }

                    }
                }
            }

            if (!StringUtils.isEmpty(tbTeacherDTO.getLast4culture())) {
                String[] arr = tbTeacherDTO.getLast4culture().split(";");
                for (int i = 3; i >= 0; i--) {
                    if (arr.length > i) {
                        if (i == 3) {
                            tbTeacherDTO.setLastCul4(arr[i].split(":")[1]);
                        } else if (i == 2) {
                            tbTeacherDTO.setLastCul3(arr[i].split(":")[1]);
                        } else if (i == 1) {
                            tbTeacherDTO.setLastCul2(arr[i].split(":")[1]);
                        } else {
                            tbTeacherDTO.setLastCul1(arr[i].split(":")[1]);
                        }
                    }
                }
            }
            if (tbTeacherDTO.getCertifiedStatus() == 3 && tbTeacherDTO.getCheckResultFlag() == 2) {//不满足条件但是认证状态为认证通过。
                judgeFlag = 1;
            }
            tbTeacherDTO.setJudgeFlag(judgeFlag);
            if (tbTeacherDTO.getDeptNameChain() != null) {
                String[] deptNameChianArr = tbTeacherDTO.getDeptNameChain().split("/");
                int i = deptNameChianArr.length - 1;
                if (i == 1) {
                    tbTeacherDTO.setDept1name(deptNameChianArr[1]);
                } else if (i == 2) {
                    tbTeacherDTO.setDept1name(deptNameChianArr[1]);
                    tbTeacherDTO.setDept2name(deptNameChianArr[2]);
                }
                if (i == 3) {
                    tbTeacherDTO.setDept1name(deptNameChianArr[1]);
                    tbTeacherDTO.setDept2name(deptNameChianArr[2]);
                    tbTeacherDTO.setDept3name(deptNameChianArr[3]);
                }
                if (i == 4) {
                    tbTeacherDTO.setDept1name(deptNameChianArr[1]);
                    tbTeacherDTO.setDept2name(deptNameChianArr[2]);
                    tbTeacherDTO.setDept3name(deptNameChianArr[3]);
                    tbTeacherDTO.setDept3name(deptNameChianArr[4]);
                }
            }
        }
        return tbTeacherDTOS;
    }


    @Override
    public TbTeacherDTO seacherInfo( TbTeacherDTO paramsDTO){
        List<String> deptIdIdList = new ArrayList<>();
        List<String> authDeptIdIdList = null;
        Set<String> depts = new HashSet<>();
        if (!StringUtils.isEmpty(paramsDTO.getDeptId())) {
            for (String deptId : paramsDTO.getDeptId().split(",")) {
                SdDept parent = sdDeptMapper.selectOne(new QueryWrapper<SdDept>().lambda().eq(SdDept::getDeptId, deptId));
                QueryWrapper<SdDept> query = new QueryWrapper<SdDept>().select("dept_id").like("dept_code_chain", parent.getDeptCodeChain());
                Set<String> temp = sdDeptMapper.selectObjs(query).stream().map(obj -> String.valueOf(obj)).collect(Collectors.toSet());
                depts.addAll(temp);
            }
            deptIdIdList.addAll(depts);
        }else {
            List<SdDept> sdDepts = sdDeptMapper.selectList(new QueryWrapper<>());
            List<Integer> allDeptIds = sdDepts.stream().map(SdDept::getDeptId).collect(Collectors.toList());
            for (Integer allDeptId : allDeptIds) {
                deptIdIdList.add(String.valueOf(allDeptId));
            }
        }
        String loginUserId = commService.getLoginUserId();
        if (commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN)) {
            //管理员
            //authDeptIdIdList = null
        } else {
            //其他人员
            //
            List<Integer> list =queryDeptForUser(loginUserId);
            List<String> list1 = new ArrayList<>();
            if(list.size()==0){
                //其他人员无权限
                authDeptIdIdList = list1;
            }else{
                //其他人员有权限
                for (Integer integer : list) {
                    list1.add(String.valueOf(integer));
                    authDeptIdIdList = list1;
                }
            }
        }
        List<String> idList = new ArrayList<>();
        if(authDeptIdIdList==null){
            //管理员
            idList = deptIdIdList;
        }else {
            if(authDeptIdIdList.size()==0){
                //其他人员无权限
            }else {
                idList = deptIdIdList.stream().filter(authDeptIdIdList::contains).collect(Collectors.toList());
            }
        }
        String deptIds = String.join(",",idList);
        paramsDTO.setDeptId(deptIds);
        return  paramsDTO;
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<TbTeacherDTO> selectByDto(TbTeacherDTO dto) {
        //List<TbTeacher> list = tbTeacherMapper.selectByExample(initExample(dto));
        List<TbTeacher> list = tbTeacherMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto), TbTeacher.class));
        List<TbTeacherDTO> tbTeacherDTOS = JSONArray.parseArray(JSONArray.toJSONString(list), TbTeacherDTO.class);

        for (TbTeacherDTO tbTeacherDTO : tbTeacherDTOS) {
//            List<TbWorker> tbWorkerList = selectTbWorkerByTeacher(tbTeacherDTO.getTeacherId());
            List<TbWorker> tbWorkerListOne = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>()
                    .like("teacher_info", tbTeacherDTO.getTeacherId())
                    .in("worker_status", 1, 2));
            List<TbWorker> tbWorkerListTwo = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>()
                    .like("teacher_info", tbTeacherDTO.getTeacherId())
                    .in("worker_status", 3));

            if (!tbWorkerListOne.isEmpty() || !tbWorkerListTwo.isEmpty()) {
                tbTeacherDTO.setHelpNum(tbWorkerListTwo.size() + "/" + tbWorkerListOne.size());
            }
            if (tbTeacherDTO.getDeptNameChain() != null) {
                String[] deptNameChianArr = tbTeacherDTO.getDeptNameChain().split(",");
                int i = deptNameChianArr.length - 1;
                if (i == 1) {
                    tbTeacherDTO.setDept1name(deptNameChianArr[2]);
                } else if (i == 2) {
                    tbTeacherDTO.setDept1name(deptNameChianArr[2]);
                    tbTeacherDTO.setDept2name(deptNameChianArr[3]);
                }
                if (i == 3) {
                    tbTeacherDTO.setDept1name(deptNameChianArr[2]);
                    tbTeacherDTO.setDept2name(deptNameChianArr[3]);
                    tbTeacherDTO.setDept3name(deptNameChianArr[4]);
                }

            }
        }
        return tbTeacherDTOS;
    }

    public List<TbWorker> selectTbWorkerByTeacher(String teacherId) {
        List<TbWorker> tbWorkerList = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>().like("teacher_info", teacherId));
        return tbWorkerList;
    }

    public Integer insertDto(TbTeacherDTO dto) {
        return insertDtoOri(dto, true);
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */

    public Integer insertDtoOri(TbTeacherDTO dto, Boolean insertCertifiedTime) {
        String userId = dto.getTeacherId();
        if (!userId.equals("")) {
            TbTeacher checkIdUser = tbTeacherMapper.selectById(dto.getTeacherId());
//            TbTeacher checkIdUser = tbTeacherMapper.selectOne(new QueryWrapper<TbTeacher>().eq("teacher_id", userId));
            if (checkIdUser != null) {
                throw new AppBusinessException("导师已添加，请重新输入");
            }
        } else {
            throw new AppBusinessException("请输入导师工号！");
        }
        //String basicInfo = dataCenterFeignClient.queryWorkerBasicInfo("{\"empCode\":\"" + userId + "\"}", commService.getEosToken());
        //JSONObject basicInfoJson = JSONObject.parseObject(basicInfo);
        //List<Map<String, String>> basicInfoList = (List<Map<String, String>>) basicInfoJson.get("data");
//        SdAllWorker sdAllWorker = sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("worker_id", userId));
        SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(userId);
        if (sdAllWorker != null) {
            //权限
         /*   if (commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN)) {
            } else {
                List<Integer> deptIdList = queryDeptForUser(commService.getLoginUserId());
                if (deptIdList.size() == 0 || !deptIdList.contains(sdAllWorker.getDirectDeptId())) {
                    throw new AppBusinessException("您无权限添加此员工为导师！");
                }
            }*/
            dto.setTeacherName(sdAllWorker.getWorkerName());
            //部门链
            StringBuilder deptCodeChain = new StringBuilder();
            StringBuilder deptNameChain = new StringBuilder();
            if (!StringUtils.isEmpty(sdAllWorker.getDept1id())) {
                deptCodeChain.append("50040000");
                deptNameChain.append("新华三");
                deptCodeChain.append("/").append(sdAllWorker.getDept1id().toString());
                deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept1id().toString()).getDeptName());

            }
            if (!StringUtils.isEmpty(sdAllWorker.getDept2id())) {
                deptCodeChain.append("/").append(sdAllWorker.getDept2id().toString());
                deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept2id().toString()).getDeptName());
            }
            if (!StringUtils.isEmpty(sdAllWorker.getDept3id())) {
                deptCodeChain.append("/").append(sdAllWorker.getDept3id().toString());
                deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept3id().toString()).getDeptName());
            }
            if (!StringUtils.isEmpty(sdAllWorker.getDept4id())) {
                deptCodeChain.append("/").append(sdAllWorker.getDept4id().toString());
                deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept4id().toString()).getDeptName());
            }
            dto.setDeptNameChain(deptNameChain.toString());
            dto.setDeptCodeChain(deptCodeChain.toString());
            //直属部门
            dto.setDirectDeptId(sdAllWorker.getDirectDeptId());
            // dto.setCompanyAge(sdAllWorker.);
        } else {
            throw new AppBusinessException("[工号：" + userId + "]用户不存在！");
        }
  /*      if (dto.getCheckResultFlag() == null || dto.getCheckResultFlag() == 1) {
            dto.setCheckResultMsg("");
        }*/
        if(dto.getCertifiedTime()==null && insertCertifiedTime){
            dto.setCertifiedTime(new Date());
        }
        dto.setCreatorInfo(commService.getLoginUserNameAndId());
        dto.setUpdatorInfo(commService.getLoginUserNameAndId());
        dto.setUpdateTime(new Date());

        Integer n = tbTeacherMapper.insertTbTeacher(JSONObject.parseObject(JSON.toJSONString(dto), TbTeacher.class));
        //日志
        commService.recordAuthChangeLog("tb_teacher", AutoOpTypeEnum.ADD, JSONObject.toJSONString(dto), "通过界面或及时认证操作添加导师");
        return n;
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(TbTeacherDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
  /*      if (dto.getCheckResultFlag() == null || dto.getCheckResultFlag() == 1) {
            dto.setCheckResultMsg("");
        }*/
        //恢复资质
        if (dto.getCertifiedStatus() == 3) {
            dto.setCheckResultMsg("");
        }
        int i = tbTeacherMapper.updateTbTeacher(JSONObject.parseObject(JSON.toJSONString(dto), TbTeacher.class));
        //取消资质邮件通知本人
        if (dto.getCertifiedStatus() == BusiEnumDefine.TEACHER_CERTIFIED_STATUS_CANCEL) {
            SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(dto.getTeacherId());
            SdAllWorker sdAllWorker1 = commService.getAllWorkerDoFromLocalCache(commService.getLoginUserId());
            String copyTo = "";
            if(sdAllWorker1!=null){
                copyTo = sdAllWorker1.getEmail();
            }
            if(sdAllWorker!=null){
                SdEmailTemplate emailTemplate = emailTemplateService.getById("TEACHER_CANCEL");
                String templateContent = emailTemplate.getEmailTemplateContent();
                String templateTitle = emailTemplate.getEmailTemplateTitle();
                templateContent = templateContent.replace("{原因}", dto.getCheckResultMsg())
                        .replace("{操作人}",commService.getLoginUserNameAndId());
                SdNoticeRecord noticeRecord = iSdNoticeRecordService.createEmailNoticeRecord("-1", dto.getTeacherId(), dto.getTeacherName(), sdAllWorker.getEmail(), templateTitle, templateContent, copyTo);
                asyncSendMessage.sendMessage(Collections.singletonList(noticeRecord));
            }
        }
        return i;
    }



    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(TbTeacherDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        //return tbTeacherMapper.deleteTbTeacher(JSONObject.parseObject(JSON.toJSONString(dto), TbTeacher.class));
        int i = tbTeacherMapper.delete(new QueryWrapper<TbTeacher>().eq("teacher_id", dto.getTeacherId()));
        commService.recordAuthChangeLog("tb_teacher", AutoOpTypeEnum.DELETE, JSONObject.toJSONString(dto), "删除导师");
        return i;
        //return tbTeacherMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description:批量删除
     * @params:List<TbTeacherDTO> dtos
     * @return: File
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer deleteDto(List<TbTeacherDTO> dtos) {
        int i = 0;
        if (dtos != null && dtos.size() > 0) {
            for (TbTeacherDTO dto : dtos) {
                if (null != dto && null != dto.getTeacherId() && !"".equals(dto.getTeacherId())) {
                    TbTeacher tcThirdOrg = JSONObject.parseObject(JSON.toJSONString(dto), TbTeacher.class);
                    i += tbTeacherMapper.deleteTbTeacher(tcThirdOrg);
                    commService.recordAuthChangeLog("tb_teacher", AutoOpTypeEnum.DELETE, JSONObject.toJSONString(dtos), "删除导师");
                    //return tcThirdOrgMapper.deleteByPrimaryKey(dto.getId());
                }
            }
        }
        return i;
    }

    /**
     * @title: initFuzzyExample
     * @description: 初始化 模糊查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    private Example initFuzzyExample(TbTeacherDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(TbTeacher.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getTeacherId() && !"".equals(dto.getTeacherId())) {
                criteriaName.andLike("TeacherId", "%" + dto.getTeacherId() + "%");
            }
            if (null != dto.getTeacherName() && !"".equals(dto.getTeacherName())) {
                criteriaName.andLike("TeacherName", "%" + dto.getTeacherName() + "%");
            }
            if (null != dto.getDeptNameChain() && !"".equals(dto.getDeptNameChain())) {
                criteriaName.andLike("DeptNameChain", "%" + dto.getDeptNameChain() + "%");
            }
            if (null != dto.getDirectDeptId() && !"".equals(dto.getDirectDeptId())) {
                criteriaName.andLike("DirectDeptId", "%" + dto.getDirectDeptId() + "%");
            }
            if (null != dto.getPostName() && !"".equals(dto.getPostName())) {
                criteriaName.andLike("PostName", "%" + dto.getPostName() + "%");
            }
            if (null != dto.getCompanyAge() && !"".equals(dto.getCompanyAge())) {
                criteriaName.andLike("CompanyAge", "%" + dto.getCompanyAge() + "%");
            }
            if (null != dto.getLast4kpi() && !"".equals(dto.getLast4kpi())) {
                criteriaName.andLike("Last4kpi", "%" + dto.getLast4kpi() + "%");
            }
            if (null != dto.getLast4culture() && !"".equals(dto.getLast4culture())) {
                criteriaName.andLike("Last4culture", "%" + dto.getLast4culture() + "%");
            }
            if (null != dto.getLastPunishRecord() && !"".equals(dto.getLastPunishRecord())) {
                criteriaName.andLike("LastPunishRecord", "%" + dto.getLastPunishRecord() + "%");
            }
            if (null != dto.getCertifiedStatus() && !"".equals(dto.getCertifiedStatus())) {
                criteriaName.andLike("CertifiedStatus", "%" + dto.getCertifiedStatus() + "%");
            }
            if (null != dto.getCheckResultFlag() && !"".equals(dto.getCheckResultFlag())) {
                criteriaName.andLike("CheckResultFlag", "%" + dto.getCheckResultFlag() + "%");
            }
            if (null != dto.getCheckResultMsg() && !"".equals(dto.getCheckResultMsg())) {
                criteriaName.andLike("CheckResultMsg", "%" + dto.getCheckResultMsg() + "%");
            }
            if (null != dto.getCertifiedTime() && !"".equals(dto.getCertifiedTime())) {
                criteriaName.andLike("CertifiedTime", "%" + dto.getCertifiedTime() + "%");
            }
            if (null != dto.getCreateTime() && !"".equals(dto.getCreateTime())) {
                criteriaName.andLike("CreateTime", "%" + dto.getCreateTime() + "%");
            }
            if (null != dto.getCreatorInfo() && !"".equals(dto.getCreatorInfo())) {
                criteriaName.andLike("CreatorInfo", "%" + dto.getCreatorInfo() + "%");
            }
            if (null != dto.getUpdateTime() && !"".equals(dto.getUpdateTime())) {
                criteriaName.andLike("UpdateTime", "%" + dto.getUpdateTime() + "%");
            }
            if (null != dto.getUpdatorInfo() && !"".equals(dto.getUpdatorInfo())) {
                criteriaName.andLike("UpdatorInfo", "%" + dto.getUpdatorInfo() + "%");
            }
            if (null != dto.getExamFlag() && !"".equals(dto.getExamFlag())) {
                criteriaName.andLike("ExamFlag", "%" + dto.getExamFlag() + "%");
            }
            if (null != dto.getExamUrl() && !"".equals(dto.getExamUrl())) {
                criteriaName.andLike("ExamUrl", "%" + dto.getExamUrl() + "%");
            }
        }
        return example;
    }

    /**
     * @title: initExample
     * @description: 初始化 精确查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    private Example initExample(TbTeacherDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(TbTeacher.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getTeacherId() && !"".equals(dto.getTeacherId())) {
                criteriaName.andEqualTo("TeacherId", dto.getTeacherId());
            }
            if (null != dto.getTeacherName() && !"".equals(dto.getTeacherName())) {
                criteriaName.andEqualTo("TeacherName", dto.getTeacherName());
            }
            if (null != dto.getDeptNameChain() && !"".equals(dto.getDeptNameChain())) {
                criteriaName.andEqualTo("DeptNameChain", dto.getDeptNameChain());
            }
            if (null != dto.getDirectDeptId() && !"".equals(dto.getDirectDeptId())) {
                criteriaName.andEqualTo("DirectDeptId", dto.getDirectDeptId());
            }
            if (null != dto.getPostName() && !"".equals(dto.getPostName())) {
                criteriaName.andEqualTo("PostName", dto.getPostName());
            }
            if (null != dto.getCompanyAge() && !"".equals(dto.getCompanyAge())) {
                criteriaName.andEqualTo("CompanyAge", dto.getCompanyAge());
            }
            if (null != dto.getLast4kpi() && !"".equals(dto.getLast4kpi())) {
                criteriaName.andEqualTo("Last4kpi", dto.getLast4kpi());
            }
            if (null != dto.getLast4culture() && !"".equals(dto.getLast4culture())) {
                criteriaName.andEqualTo("Last4culture", dto.getLast4culture());
            }
            if (null != dto.getLastPunishRecord() && !"".equals(dto.getLastPunishRecord())) {
                criteriaName.andEqualTo("LastPunishRecord", dto.getLastPunishRecord());
            }
            if (null != dto.getCertifiedStatus() && !"".equals(dto.getCertifiedStatus())) {
                criteriaName.andEqualTo("CertifiedStatus", dto.getCertifiedStatus());
            }
            if (null != dto.getCheckResultFlag() && !"".equals(dto.getCheckResultFlag())) {
                criteriaName.andEqualTo("CheckResultFlag", dto.getCheckResultFlag());
            }
            if (null != dto.getCheckResultMsg() && !"".equals(dto.getCheckResultMsg())) {
                criteriaName.andEqualTo("CheckResultMsg", dto.getCheckResultMsg());
            }
            if (null != dto.getCertifiedTime() && !"".equals(dto.getCertifiedTime())) {
                criteriaName.andEqualTo("CertifiedTime", dto.getCertifiedTime());
            }
            if (null != dto.getCreateTime() && !"".equals(dto.getCreateTime())) {
                criteriaName.andEqualTo("CreateTime", dto.getCreateTime());
            }
            if (null != dto.getCreatorInfo() && !"".equals(dto.getCreatorInfo())) {
                criteriaName.andEqualTo("CreatorInfo", dto.getCreatorInfo());
            }
            if (null != dto.getUpdateTime() && !"".equals(dto.getUpdateTime())) {
                criteriaName.andEqualTo("UpdateTime", dto.getUpdateTime());
            }
            if (null != dto.getUpdatorInfo() && !"".equals(dto.getUpdatorInfo())) {
                criteriaName.andEqualTo("UpdatorInfo", dto.getUpdatorInfo());
            }
            if (null != dto.getExamFlag() && !"".equals(dto.getExamFlag())) {
                criteriaName.andEqualTo("ExamFlag", dto.getExamFlag());
            }
            if (null != dto.getExamUrl() && !"".equals(dto.getExamUrl())) {
                criteriaName.andEqualTo("ExamUrl", dto.getExamUrl());
            }
        }
        return example;
    }

    /**
     * @title: importTeacherList
     * @description: 导师导入
     * @params: [ List<TbTeacherDTO> ]
     * @return: Integer
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer importTeacherList(MultipartFile file) {
        String fileContent = commService.parseExcelByTemplate("TEACHER_IMPORT", file);
        JSONArray jsonArray = JSONArray.parseArray(fileContent);
        // List<TbTeacherDTO> sdTeacherDTOS = JSONArray.parseArray(fileContent, TbTeacherDTO.class);
        QueryWrapper queryWrapper = new QueryWrapper<TbTeacher>();
        List<TbTeacher> tbTeacherDTOSHave = tbTeacherMapper.selectList(queryWrapper);//数据库中已存在的用户
        List<TbTeacherDTO> tbTeachersDTOInsert = new ArrayList<>();//新增
        List<TbTeacherDTO> tbTeachersdDTOUpdate = new ArrayList<>();//更新
        List<String> userIdList = tbTeacherDTOSHave.stream().map(TbTeacher::getTeacherId).collect(Collectors.toList());
//        List<Integer> deptIdList = queryDeptForUser(commService.getLoginUserId());
        List<TbTeacherDTO> tbTeacherDTOS = new ArrayList<>();
        int i = 1;
        for (Object jsonObj : jsonArray) {
            try {
                i++;
                JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
                //TbTeacherDTO sdTeacherDTO = JSONObject.parseObject(jsonObject.toJSONString(), TbTeacherDTO.class);

                TbTeacherDTO tbTeacherDTO = new TbTeacherDTO();
                String teacherId = jsonObject.get("teacherId").toString();
                if (!StringUtils.isEmpty(teacherId)) {
                    SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(teacherId);
//                    SdAllWorker sdAllWorker = sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("worker_id", teacherId));
                    tbTeacherDTO.setTeacherId(teacherId);
                    if (!StringUtils.isEmpty(sdAllWorker)) {
                        //权限
                        if (commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN)) {
                        } else {
                            List<Integer> deptIdList = queryDeptForUser(commService.getLoginUserId());

                            if (deptIdList.size() == 0 || !deptIdList.contains(sdAllWorker.getDirectDeptId())) {
                                throw new AppBusinessException("您无权限添加此员工为导师！");
                            }
                        }
                        tbTeacherDTO.setTeacherName(sdAllWorker.getWorkerName());
                        //部门链
                        StringBuilder deptCodeChain = new StringBuilder();
                        StringBuilder deptNameChain = new StringBuilder();
                        if (!StringUtils.isEmpty(sdAllWorker.getDept1id())) {
                            deptCodeChain.append("50040000");
                            deptNameChain.append("新华三");
                            deptCodeChain.append("/").append(sdAllWorker.getDept1id().toString());
                            deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept1id().toString()).getDeptName());

                        }
                        if (!StringUtils.isEmpty(sdAllWorker.getDept2id())) {
                            deptCodeChain.append("/").append(sdAllWorker.getDept2id().toString());
                            deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept2id().toString()).getDeptName());
                        }
                        if (!StringUtils.isEmpty(sdAllWorker.getDept3id())) {
                            deptCodeChain.append("/").append(sdAllWorker.getDept3id().toString());
                            deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept3id().toString()).getDeptName());
                        }
                        if (!StringUtils.isEmpty(sdAllWorker.getDept4id())) {
                            deptCodeChain.append("/").append(sdAllWorker.getDept4id().toString());
                            deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept4id().toString()).getDeptName());
                        }
                        tbTeacherDTO.setDeptNameChain(deptNameChain.toString());
                        tbTeacherDTO.setDeptCodeChain(deptCodeChain.toString());
                        //直属部门
                        tbTeacherDTO.setDirectDeptId(sdAllWorker.getDirectDeptId());
                        // dto.setCompanyAge(sdAllWorker.);
/*                    String checkResultCh = jsonObject.get("checkResultFlag").toString();
                    int checkResultFlag = -1;

                    if (!StringUtils.isEmpty(checkResultCh)) {
                        switch (checkResultCh) {
                            case "满足":
                                checkResultFlag = 1;
                                break;
                            case "不满足":
                                checkResultFlag = 2;
                                break;
                        }
                    }
                    if (checkResultFlag == 1) {
                        tbTeacherDTO.setCheckResultFlag(checkResultFlag);
                        tbTeacherDTO.setCheckResultMsg("");
                    } else if (checkResultFlag == 2) {
                        tbTeacherDTO.setCheckResultFlag(checkResultFlag);//不满足时才检测不满足条件说明
                        String checkResultMsg = jsonObject.get("checkResultMsg").toString();
                        if (!StringUtils.isEmpty(checkResultMsg)) {
                            tbTeacherDTO.setCheckResultMsg(checkResultMsg);
                        }
                    }*/

//                    if (StringUtils.isEmpty(jsonObject.get("checkResultFlag").toString()) || Integer.parseInt(jsonObject.get("checkResultFlag").toString()) == 1) {
//                        sdTeacherDTO.setCheckResultMsg("");
//                    }
                        String certifiedStatusCh = jsonObject.get("certifiedStatus").toString();
                        int certifiedStatus = -1;
                        if (!StringUtils.isEmpty(certifiedStatusCh)) {
                            switch (certifiedStatusCh) {
                            /*case "未认证":
                                certifiedStatus = 1;
                                break;
                            case "资质不符":
                                certifiedStatus = 2;
                                break;*/
                                case "认证通过":
                                    certifiedStatus = 3;
                                    break;
                                case "取消资格":
                                    certifiedStatus = 4;
                                    break;
                            }
                            tbTeacherDTO.setCertifiedStatus(certifiedStatus);
                            //根据认证状态校验认证时间
                            if (certifiedStatus == 3) {//认证通过
                                String certifiedTime = jsonObject.get("certifiedTime").toString();
                                //时间有值则用，没有就设置当前时间
                                if (!StringUtils.isEmpty(certifiedTime)) {
                                    certifiedTime = certifiedTime.replaceAll("\\.", "-").replaceAll("/", "-");
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                    try {
                                        Date certifiedDate = sdf.parse(certifiedTime);
                                        Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(certifiedDate);
                                        calendar.set(Calendar.HOUR_OF_DAY, 0);
                                        calendar.set(Calendar.MINUTE, 0);
                                        calendar.set(Calendar.SECOND, 0);
                                        certifiedDate = calendar.getTime();
                                        tbTeacherDTO.setCertifiedTime(certifiedDate);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    tbTeacherDTO.setCertifiedTime(new Date());
                                }
                            }
             /*           else {//认证状态不是认证通过，认证时间直接置空
                            tbTeacherDTO.setCertifiedTime(null);
                        }*/
                        } else {
//                        throw new AppBusinessException("请输入[工号" + teacherId + "]的认证状态：{认证通过/取消资格}！");
                            //不传状态，默认通过和设置当前时间
                            tbTeacherDTO.setCertifiedStatus(3);
                            tbTeacherDTO.setCertifiedTime(new Date());

                        }
                        tbTeacherDTO.setUpdateTime(new Date());
                        tbTeacherDTO.setUpdatorInfo(commService.getLoginUserNameAndId());
                        if (!userIdList.contains(jsonObject.get("teacherId").toString())) {
                            tbTeacherDTO.setCreatorInfo(commService.getLoginUserNameAndId());
                        }
                        tbTeacherDTOS.add(tbTeacherDTO);
                    } else {
//                    throw new AppBusinessException("系统中不存在工号：" + teacherId + "用户！");
                        log.info("系统中不存在工号：" + teacherId + "用户！");
                        continue;
                    }
                } else {
//                throw new AppBusinessException("第" + i + "行的导师工号为空！");
                    log.info("第" + i + "行的导师工号为空！");
                    continue;
                }
                log.info("第" + i + "行数据处理完毕！");
            }catch (Exception e){
                continue;
            }
        }

//            String basicInfo = dataCenterFeignClient.queryWorkerBasicInfo("{\"empCode\":\"" + teacherId + "\"}", commService.getEosToken());
//            JSONObject basicInfoJson = JSONObject.parseObject(basicInfo);
//            List<Map<String, String>> basicInfoList = (List<Map<String, String>>) basicInfoJson.get("data");

        // SdAllWorker sdAllWorker = sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("worker_id", teacherId));


        for (TbTeacherDTO tbTeacherDTO1 : tbTeacherDTOS) {
            if (userIdList.contains(tbTeacherDTO1.getTeacherId())) {
                tbTeachersdDTOUpdate.add(tbTeacherDTO1);
            } else {
                tbTeachersDTOInsert.add(tbTeacherDTO1);
            }
        }
        List<TbTeacher> tbTeacherInsertList = JSONArray.parseArray(JSONArray.toJSONString(tbTeachersDTOInsert), TbTeacher.class);
        List<TbTeacher> tbTeacherUpdateList = JSONArray.parseArray(JSONArray.toJSONString(tbTeachersdDTOUpdate), TbTeacher.class);

        int updateNum = 0;
        int insertNum = 0;
        //日志
        for (TbTeacher tbTeacher : tbTeacherUpdateList) {
            updateNum = updateNum + tbTeacherMapper.updateTbTeacher(tbTeacher);
            log.info("更新一条导师数据成功！");
            commService.recordAuthChangeLog("tb_teacher", AutoOpTypeEnum.UPDATE, JSONObject.toJSONString(tbTeacher), "通过导入更新导师");
            // updateNum++;
        }
//        tbTeacherUpdateList.
        List<String> list = new ArrayList<>();
        for (TbTeacher tbTeacher : tbTeacherInsertList) {
            if(list.contains(tbTeacher.getTeacherId())){
                continue;
            }
            insertNum = insertNum + tbTeacherMapper.insertTbTeacher(tbTeacher);
            list.add(tbTeacher.getTeacherId());

            log.info("插入一条导师数据成功！");
            commService.recordAuthChangeLog("tb_teacher", AutoOpTypeEnum.UPDATE, JSONObject.toJSONString(tbTeacher), "通过导入新建导师");
            // insertNum++;
        }
        return updateNum + insertNum;
    }

    /**
     * @title: download
     * @description: 导师导出
     * @params:
     * @return: File
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public File download(TbTeacherDTO paramsDTO, String templateCode, String fileName) {
        List<TbTeacherDTO> tbTeacherDTOS = selectFuzzyByDto(paramsDTO);
        tbTeacherDTOS.forEach(tbTeacherDTO -> {
            if (tbTeacherDTO.getCheckResultFlag() != null) {
                if (tbTeacherDTO.getCheckResultFlag() == 1) {
                    tbTeacherDTO.setCheckResultFlagCh("满足");
                } else if (tbTeacherDTO.getCheckResultFlag() == 2) {
                    tbTeacherDTO.setCheckResultFlagCh("不满足");
                } else {
                    tbTeacherDTO.setCheckResultFlagCh("");
                }
            }
            if (tbTeacherDTO.getCertifiedStatus() == 1) {
                tbTeacherDTO.setCertifiedStatusCh("未认证");
            } else if (tbTeacherDTO.getCertifiedStatus() == 2) {
                tbTeacherDTO.setCertifiedStatusCh("资质不符");
            } else if (tbTeacherDTO.getCertifiedStatus() == 3) {
                tbTeacherDTO.setCertifiedStatusCh("认证通过");
            } else if (tbTeacherDTO.getCertifiedStatus() == 4) {
                tbTeacherDTO.setCertifiedStatusCh("取消资格");
            } else {
                tbTeacherDTO.setCertifiedStatusCh("");
            }
            if (tbTeacherDTO.getExamFlag() != null) {
                if (tbTeacherDTO.getExamFlag() == 1) {
                    tbTeacherDTO.setExamFlagCh("未开启");
                }
                if (tbTeacherDTO.getExamFlag() == 2) {
                    tbTeacherDTO.setExamFlagCh("开启");
                } else {
                    tbTeacherDTO.setExamFlagCh("");
                }
            }
        });
        return commService.generateExportFile(fileName, templateCode, (List) tbTeacherDTOS);
    }


    @Override
    public String checkWorker(String workerId) {
//        Integer checkIsTeacher = tbTeacherMapper.checkIsTeacher(workerId);
        TbTeacher tbTeacher = tbTeacherMapper.selectOne(new QueryWrapper<TbTeacher>().eq("teacher_id", workerId));
        List<TbTeacherDTO> teacherDTOS = sdAllWorkerService.checkTeacherAbility(Collections.singletonList(workerId));
        //不在导师库中
        if (Objects.isNull(tbTeacher)){
            //有认证资格的工号
            if (!CollectionUtils.isEmpty(teacherDTOS)){
                List<String> passIds = teacherDTOS.stream().map(TbTeacherDTO::getTeacherId).collect(Collectors.toList());
                return passIds.get(0);
            }else{
                return "-1";
            }
        }else{
            //在导师表中但不符合导师资质并且状态不是认证通过
            if (CollectionUtils.isEmpty(teacherDTOS) && tbTeacher.getCertifiedStatus() != 3){
                return "-1";
            }else{
                TbTeacher teacher = tbTeacherMapper.selectOne(new QueryWrapper<TbTeacher>().eq("teacher_id", teacherDTOS.get(0).getTeacherId()));
                //正在导师认证中的员工
                if (teacher.getCertifiedStatus() == 5){
                    return "-2";
                }
                //在导师表中符合导师认证资质但是认证不通过的员工
                if (teacher.getCertifiedStatus() != 3 && teacher.getCertifiedStatus() != 5){
                    return teacherDTOS.get(0).getTeacherId();
                }
            }
        }
            return null;
    }

    /**
     * 选择导师后 若在导师库则继续，否则进行导师即时认证
     * @param workerId
     */
    public void checkSelectTeacher(String workerId) {
//        TbTeacher tbTeacher = tbTeacherMapper.selectOne(new QueryWrapper<TbTeacher>().eq("teacher_id", workerId));
//        if (Objects.isNull(tbTeacher)){
            List<String> passIds = SpringUtil.getBean(ITbTeacherService.class).instantCertificate(Collections.singletonList(workerId));
            if (passIds.isEmpty()) {
                throw new AppBusinessException("所选员工不符合资质，请您换人或为此人线下申请特批流程");
//            }
        }
    }

    /**
     * 导师认证
     * @param workerIdList
     */
    @Transactional(rollbackFor = Exception.class)
    public List<String> instantCertificate(List<String> workerIdList) {
        //有认证资格的工号
        List<TbTeacherDTO> teacherDTOS = sdAllWorkerService.checkTeacherAbility(workerIdList);
        List<String> passIds = null;
        List<String> passIdList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(teacherDTOS)) {
            passIds = teacherDTOS.stream().map(TbTeacherDTO::getTeacherId).collect(Collectors.toList());
            passIds.forEach(id -> {
                TbTeacher tbTeacher = tbTeacherMapper.selectOne(new QueryWrapper<TbTeacher>().eq("teacher_id", id));
                if (Objects.nonNull(tbTeacher)){
                    //导师库中已有，状态不为通过和进行中的才更新和邮件
                    if(!tbTeacher.getCertifiedStatus().equals(CertifiedStatusEnum.PASSED.getCode())
                            &&!tbTeacher.getCertifiedStatus().equals(CertifiedStatusEnum.UNDER_CERTIFICATION.getCode())){
                        tbTeacher.setCertifiedStatus(CertifiedStatusEnum.UNDER_CERTIFICATION.getCode());
                        tbTeacherMapper.updateById(tbTeacher);
                        passIdList.add(id);
                    }
                }else{
//                    TbTeacherCertificationInfo tbTeacherCertificationInfo = tbTeacherCertificationInfoMapper.selectById(id);
                    TbTeacherDTO teacherDTO = new TbTeacherDTO();
                    teacherDTO.setTeacherId(id);
//                    if(Objects.nonNull(tbTeacherCertificationInfo)){
//                        teacherDTO.setLast4kpi(tbTeacherCertificationInfo.getLast4kpi());
//                        teacherDTO.setLast4culture(tbTeacherCertificationInfo.getLast4culture());
//                        teacherDTO.setLastPunishRecord(tbTeacherCertificationInfo.getLastPunishRecord());
//                    }
                    teacherDTO.setCertifiedStatus(CertifiedStatusEnum.UNDER_CERTIFICATION.getCode());
                    insertDtoOri(teacherDTO, false);
                    passIdList.add(id);
                }
            });
            LambdaQueryWrapper<SdAllWorker> workerWrapper = new LambdaQueryWrapper<>();
            workerWrapper.in(SdAllWorker::getWorkerId, passIdList);
            List<SdAllWorker> passWorkers = sdAllWorkerMapper.selectList(workerWrapper);
            sendMailToCollegeOrLeader(passWorkers, "CERTIFICATION_NOTICE_EMAIL_EDU", "大讲堂接口人", dajiangtangEmail);
        }
        return passIdList;
    }

    /**
     * 发送邮件通知大讲堂接口人 or 主管
     * @param passWorkers
     * @param emailTemplateName CERTIFICATION_NOTICE_EMAIL_EDU大讲堂 CERTIFICATION_NOTICE_EMAIL_LEAD主管
     */
    public void sendMailToCollegeOrLeader(List<SdAllWorker> passWorkers, String emailTemplateName, String targetName, String targetEmail) {

        SdEmailTemplate template = emailTemplateService.getById(emailTemplateName);
        if (template == null) {
            return;
        }
        String content = template.getEmailTemplateContent();

        SdNoticeRecord noticeRecord = new SdNoticeRecord();
        noticeRecord.setNoticeId(IdWorker.nextId() + "");
        noticeRecord.setFlowId("-1");
        noticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
        noticeRecord.setTargetName(targetName);
        noticeRecord.setTargetEmail(targetEmail);//todo 待确认大讲堂接口人
        noticeRecord.setCreateTime(new Date());
        noticeRecord.setNoticeTitle(template.getEmailTemplateTitle());
        if (passWorkers.size() <= 10) {
            StringBuilder workerSb = new StringBuilder();
            passWorkers.forEach(workerDO -> {
                workerSb.append(workerDO.getWorkerName()).append("/").append(workerDO.getWorkerId()).append(" ");
                if (StringUtils.hasText(commService.getDeptName(workerDO.getDept1id()))) {
                    workerSb.append(commService.getDeptName(workerDO.getDept1id()));
                }
                if (StringUtils.hasText(commService.getDeptName(workerDO.getDept2id()))) {
                    workerSb.append("/").append(commService.getDeptName(workerDO.getDept2id()));
                }
                if (StringUtils.hasText(commService.getDeptName(workerDO.getDept3id()))) {
                    workerSb.append("/").append(commService.getDeptName(workerDO.getDept3id()));
                }
                if (StringUtils.hasText(commService.getDeptName(workerDO.getDept4id()))) {
                    workerSb.append("/").append(commService.getDeptName(workerDO.getDept4id()));
                }
                workerSb.append("<br>");
            });
            String replace = content.replace("{员工}", workerSb);
            noticeRecord.setNoticeContent(replace);
            commService.sendMessage(noticeRecord);
        } else {
            List<CertificateDTO> workerList = new ArrayList<>();
            passWorkers.forEach(workerDO -> {
                CertificateDTO workerDTO = new CertificateDTO();
                workerDTO.setWorkerId(workerDO.getWorkerId());
                workerDTO.setWorkerName(workerDO.getWorkerName());
                workerDTO.setDept1name(commService.getDeptName(workerDO.getDept1id()));
                workerDTO.setDept2name(commService.getDeptName(workerDO.getDept2id()));
                workerDTO.setDept3name(commService.getDeptName(workerDO.getDept3id()));
                workerDTO.setDept4name(commService.getDeptName(workerDO.getDept4id()));
                workerList.add(workerDTO);
            });

            File attachment = commService.generateExportFile("满足导师任职资格员工名单.xlsx", "CERTIFICATE_ATTACHMENT", (List) workerList);
            String replace = content.replace("{员工}", "名单详见附件");
            noticeRecord.setNoticeContent(replace);
            commService.sendMessage(noticeRecord, Collections.singletonList(attachment));
        }
    }

    /**
     * 每季度第一天从allworker表查现在不是导师的人中的三四级部门的员工中满足初次认证导师资格条件的员工，导师邮件推送给主管，让主管在菜单里发起认证申请，
     */
    @Transactional
    public void autoInfoLeaderToCertificate() {
        List<SdAllWorker> notTeacher = tbTeacherMapper.selectWorkerNotTeacher();
        List<TbTeacher> tbTeacherList = tbTeacherMapper.selectList(new QueryWrapper<TbTeacher>().notIn("certified_status", Arrays.asList("3", "5")));
        tbTeacherList.forEach(tbTeacher -> {
            SdAllWorker sdAllWorker = sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("worker_id", tbTeacher.getTeacherId()));
            notTeacher.add(sdAllWorker);
        });
        //在导师表中符合导师认证资质但是认证不通过的员工
        List<TbTeacherDTO> tbTeacherDTOList = sdAllWorkerService.checkTeacherAbility(tbTeacherList.stream().map(TbTeacher::getTeacherId).collect(Collectors.toList()));
        Map<String, SdAllWorker> notTeacherMap = notTeacher.stream().collect(Collectors.toMap(SdAllWorker::getWorkerId, o -> o, (k1, k2) -> k1));
        //符合条件的工号
        List<TbTeacherDTO> teacherDTOS = sdAllWorkerService.checkTeacherAbility(new ArrayList<>(notTeacherMap.keySet()));
        if (!CollectionUtils.isEmpty(tbTeacherDTOList)){
            teacherDTOS.addAll(tbTeacherDTOList);
            teacherDTOS = teacherDTOS.stream().distinct().collect(Collectors.toList());
        }
        List<String> eligibleIds = teacherDTOS.stream().map(TbTeacherDTO::getTeacherId).collect(Collectors.toList());
        Map<String, List<SdAllWorker>> leaderAuthWorkerMap = new HashMap<>();

        eligibleIds.forEach(eligibleId -> {
            SdAllWorker notTeacherWorker = notTeacherMap.get(eligibleId);
            Integer dept4id = notTeacherWorker.getDept4id();
            Integer dept3id = notTeacherWorker.getDept3id();
            SdDept dept = null;
            if (dept4id != null) {
                dept = commService.getDept(dept4id);
            } else if (dept3id != null) {
                dept = commService.getDept(dept3id);
            }
            if (dept != null) {
                String managerId = dept.getDeptManagerId();
                List<SdAllWorker> authWorkers = leaderAuthWorkerMap.get(managerId);
                if (CollectionUtils.isEmpty(authWorkers)) {
                    List<SdAllWorker> list = new ArrayList<>();
                    list.add(notTeacherMap.get(eligibleId));
                    leaderAuthWorkerMap.put(managerId, list);
                } else {
                    authWorkers.add(notTeacherMap.get(eligibleId));
                }
            }
        });

        leaderAuthWorkerMap.forEach((leaderId, workerList) -> {
            SdAllWorker leader = commService.getAllWorkerDoFromLocalCache(leaderId);
            if (leader != null) {
                //一级主管不发生邮件
                List<SdDept> sdDepts = sdDeptMapper.selectList(new QueryWrapper<SdDept>().lambda()
                        .like(SdDept::getDeptManagerId,leaderId)
                        .eq(SdDept::getDeptLevel,1));
                if(CollectionUtils.isEmpty(sdDepts)){
                    sendMailToCollegeOrLeader(workerList, "CERTIFICATION_NOTICE_EMAIL_LEAD", leader.getWorkerName(), leader.getEmail());
                }
            }
        });
        // 往导师认证表 tb_teacher_certification_info 中插入数据
//            List<String> workerIdList = workerList.stream().map(SdAllWorker::getWorkerId).collect(Collectors.toList());
        // 符合条件的工号
//            List<TbTeacherDTO> tbTeacherDTOS = sdAllWorkerService.checkTeacherAbility(workerIdList);
//            List<String> teacherIdList = tbTeacherDTOS.stream().map(TbTeacherDTO::getTeacherId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(teacherDTOS)){
            //插入前先将之前的数据清空
            tbTeacherCertificationInfoMapper.delete(new QueryWrapper<TbTeacherCertificationInfo>());
            for (TbTeacherDTO tbTeacherDTO : teacherDTOS) {
                SdAllWorker sdAllWorker = sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("worker_id", tbTeacherDTO.getTeacherId()));
                TbTeacherCertificationInfo tbTeacherCertificationInfo = new TbTeacherCertificationInfo();
                tbTeacherCertificationInfo.setWorkerId(sdAllWorker.getWorkerId());
                tbTeacherCertificationInfo.setWorkerName(sdAllWorker.getWorkerName());
                tbTeacherCertificationInfo.setAge(sdAllWorker.getAge());
                tbTeacherCertificationInfo.setEntryTime(sdAllWorker.getJoinDate());
                tbTeacherCertificationInfo.setLast4kpi(tbTeacherDTO.getLast4kpi());
                tbTeacherCertificationInfo.setLast4culture(tbTeacherDTO.getLast4culture());
                tbTeacherCertificationInfo.setLastPunishRecord(tbTeacherDTO.getLastPunishRecord());
                tbTeacherCertificationInfo.setCheckTime(new Date());
                //查询该员工有无导师认证资格审核记录
                List<TbApprovalRecord> tbApprovalRecords = tbApprovalRecordMapper.selectList(new QueryWrapper<TbApprovalRecord>().eq("flow_id", sdAllWorker.getWorkerId())
                        .eq("approval_type", BusiEnumDefine.TEACHER_CERTIFICATION_APPROVAL));
//                TbApprovalRecord tbApprovalRecord = null;
                if (!CollectionUtils.isEmpty(tbApprovalRecords)){
                    tbApprovalRecords.sort(Comparator.comparing(TbApprovalRecord::getApprovalTime).reversed());
                    //获取时间最近的一条记录
                    TbApprovalRecord tbApprovalRecord = tbApprovalRecords.get(0);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date approvalTime = tbApprovalRecord.getApprovalTime();
                    String str = sdf.format(approvalTime);
                    String[] strArr = str.split("-");
                    tbTeacherCertificationInfo.setRemark(strArr[0] + "年" + strArr[1] + "月" + strArr[2] + "日" + tbApprovalRecord.getApprovalNote());
                }
                //部门链
                StringBuilder deptCodeChain = new StringBuilder();
                StringBuilder deptNameChain = new StringBuilder();
                Integer directDeptId = sdAllWorker.getDirectDeptId();
                SdDept sdDept = commService.getSdDept(directDeptId.toString());
                if (Objects.nonNull(sdDept)){
                    deptCodeChain.append(sdDept.getDeptCodeChain());
                    deptNameChain.append(sdDept.getDeptNameChain());
                }else{
                    continue;
                }
                tbTeacherCertificationInfo.setDeptNameChain(deptNameChain.toString());
                tbTeacherCertificationInfo.setDeptCodeChain(deptCodeChain.toString());
                tbTeacherCertificationInfoMapper.insert(tbTeacherCertificationInfo);
            }
        }
    }

    @Override
    public List<TbTeacher> getTeacherByKeyWord(String key) {
        PageHelper.startPage(1, 20);
        return tbTeacherMapper.getTeacherByKeyWord(key);
    }

    /*
    * 更新导师部门
    * */
    public void syncTeacherDept(){
        List<TbTeacher> tbTeacherList = tbTeacherMapper.selectList(new QueryWrapper<>());
        for (TbTeacher tbTeacher : tbTeacherList) {
            SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(tbTeacher.getTeacherId());
            if(!ObjectUtils.isEmpty(sdAllWorker)){
                //部门链
                StringBuilder deptCodeChain = new StringBuilder();
                StringBuilder deptNameChain = new StringBuilder();
                if (!StringUtils.isEmpty(sdAllWorker.getDept1id())) {
                    deptCodeChain.append("50040000");
                    deptNameChain.append("新华三");
                    deptCodeChain.append("/").append(sdAllWorker.getDept1id().toString());
                    deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept1id().toString()).getDeptName());

                }
                if (!StringUtils.isEmpty(sdAllWorker.getDept2id())) {
                    deptCodeChain.append("/").append(sdAllWorker.getDept2id().toString());
                    deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept2id().toString()).getDeptName());
                }
                if (!StringUtils.isEmpty(sdAllWorker.getDept3id())) {
                    deptCodeChain.append("/").append(sdAllWorker.getDept3id().toString());
                    deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept3id().toString()).getDeptName());
                }
                if (!StringUtils.isEmpty(sdAllWorker.getDept4id())) {
                    deptCodeChain.append("/").append(sdAllWorker.getDept4id().toString());
                    deptNameChain.append("/").append(commService.getSdDept(sdAllWorker.getDept4id().toString()).getDeptName());
                }
                if(!tbTeacher.getDirectDeptId().equals(sdAllWorker.getDirectDeptId())
                        ||!tbTeacher.getDeptCodeChain().equals(deptNameChain.toString())){
                    tbTeacher.setDirectDeptId(sdAllWorker.getDirectDeptId());
                    tbTeacher.setDeptNameChain(deptNameChain.toString());
                    tbTeacher.setDeptCodeChain(deptCodeChain.toString());
                    XxlJobLogger.log(JSONObject.toJSONString(tbTeacher));
                    tbTeacherMapper.updateTbTeacher(tbTeacher);
                }
            }
        }
    }

    /**
     * @title: syncGrade
     * @description:同步导师绩效，文化，奖惩记录
     * @params:
     * @return: Integer
     * @createTime: 2022-02-22
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer syncGrade() {
        String[] periods = CommonUtil.getLastSeasonsByNum(new Date(), 4);
        //获取工号
        List<TbTeacher> tbTeacherList = tbTeacherMapper.selectList(new QueryWrapper<>());
        List<String> empCodeList = tbTeacherList.stream().map(TbTeacher::getTeacherId).collect(Collectors.toList());
        //获取绩效
        List<PmGradeDTO> pmGradeList = getPmGradeList(empCodeList);
        List<PmGradeDTO> pmGradeDTOList = new ArrayList<>();
        pmGradeList.forEach(pmGrade -> {
           if(pmGrade.getEvaluationType()==90){
               pmGradeDTOList.add(pmGrade);
           }
       });
        Map<String, List<PmGradeDTO>> gradeMap = pmGradeDTOList.stream().collect(
                Collectors.groupingBy(pmGradeDTO -> pmGradeDTO.getWorkerId()));
        //获取奖惩信息
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.YEAR, -2);
        Date twoYearsBefore = calendar.getTime();
        Map<String, String> publishDataMap = syncPunishData(twoYearsBefore,new Date());
        //获取文化
        List<PmGradeDTO> pmCultureList = getPmCultureList(empCodeList);
        Map<String, List<PmGradeDTO>> cultureMap = pmCultureList.stream().collect(
                Collectors.groupingBy(pmGradeDTO -> pmGradeDTO.getWorkerId()));

        Integer i = 0;
        //设置字段
        for (TbTeacher tbTeacher : tbTeacherList) {
            //设置惩处信息
            if (!CollectionUtils.isEmpty(publishDataMap)) {
                String publishRecord = publishDataMap.get(tbTeacher.getTeacherId());
                if (!StringUtils.isEmpty(publishRecord)) {
                    tbTeacher.setLastPunishRecord(publishRecord);
                }
            }
            //设置绩效
            List<PmGradeDTO> gradeList = gradeMap.get(tbTeacher.getTeacherId());
            Map<String, String> newGradeMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(gradeList)) {
                StringBuilder gradeStr = new StringBuilder();
                List<String> periodNameList = new ArrayList<>();
                gradeList.forEach(pmGradeDTO -> {
                    periodNameList.add(pmGradeDTO.getGradePeriod());
                    String periodName = pmGradeDTO.getGradePeriod();
                    String kpi = pmGradeDTO.getGradeValue();
                    newGradeMap.put(periodName, kpi);
                });
//                List<String> sortedperiodNameList = CommonUtil.sortedPeridName(periodNameList);
                for (String s : periods) {
                    if(!StringUtils.isEmpty(newGradeMap.get(s))){
                        gradeStr.append(s).append(":").append(newGradeMap.get(s)).append(";");
                    }else {
                        gradeStr.append(s).append(":").append("-").append(";");
                    }
                }
                tbTeacher.setLast4kpi(gradeStr.substring(0,gradeStr.length()-1));
            }
            //设置文化
            List<PmGradeDTO> cultureList = cultureMap.get(tbTeacher.getTeacherId());
            Map<String, String> newCultureMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(cultureList)) {
                List<String> periodNameList = new ArrayList();
                StringBuilder cultureStr = new StringBuilder();
                cultureList.forEach(pmGradeDTO -> {
                    String date = pmGradeDTO.getEvaluationBeginDate().split(" ")[0];//2020-10-01;2021-01-01
                    String periodName = CommonUtil.getPeriodName(date);
                    String culture = pmGradeDTO.getEvaluationResult();
                    if (pmGradeDTO.getEvaluationTypeC() == 90) {
                        newCultureMap.put(periodName, culture);
                        periodNameList.add(periodName);
                    }
                });
//                List<String> sortedperiodNameList = CommonUtil.sortedPeridName(periodNameList);
                for (String s : periods) {
                    if(!StringUtils.isEmpty(newCultureMap.get(s))){
                        cultureStr.append(s).append(":").append(newCultureMap.get(s)).append(";");
                    }else {
                        cultureStr.append(s).append(":").append("-").append(";");
                    }
                }
                tbTeacher.setLast4culture(cultureStr.substring(0,cultureStr.length()-1));
            }
            //更新
            i = i + tbTeacherMapper.updateTbTeacher(tbTeacher);
        }
        List<TbTeacherDTO> tbTeacherDTOS = JSONArray.parseArray(JSONArray.toJSONString(tbTeacherList), TbTeacherDTO.class);
        changeTeacherResult(tbTeacherDTOS);
        syncTeacherDept();
        return i;
    }

    //导师绩效
    @Override
    public List<PmGradeDTO> getPmGradeList(List<String> empCodeList) {
        String[] period = CommonUtil.getLastSeasonsByNum(new Date(), 4);
        //List<String> seasonList = Arrays.asList(period);
        EmpInfoDTO empDto = new EmpInfoDTO();
        empDto.setPeriod(period);
        empDto.setEmpCode(empCodeList);
        empDto.setEmp_code(empCodeList);
        String gradeString = dataCenterFeignClient.queryPdWorkerGrade(JSONObject.toJSONString(empDto), commService.getInventoryToken());
        Result<List<PmGradeDTO>> gradeListResult = JSON.parseObject(gradeString, new TypeReference<Result<List<PmGradeDTO>>>() {
        });
        List<PmGradeDTO> gradeList = gradeListResult.getData();
        return gradeList;
    }

    //导师文化
    @Override
    public List<PmGradeDTO> getPmCultureList(List<String> empCodeList) {
        EmpInfoDTO empDto = new EmpInfoDTO();
        Map<String, String> dataMap = getCurrentAndOldQuarterStartTime();
        empDto.setBegDate(dataMap.get("old"));
        empDto.setEndDate(dataMap.get("now"));
        empDto.setEmpCode(empCodeList);
        empDto.setEmp_code(empCodeList);
        String cultureString = dataCenterFeignClient.queryWorkerCultura(JSONObject.toJSONString(empDto), commService.getInventoryToken());
        Result<List<PmGradeDTO>> cultureListResult = JSON.parseObject(cultureString, new TypeReference<Result<List<PmGradeDTO>>>() {
        });
        List<PmGradeDTO> cultureList = cultureListResult.getData();
        return cultureList;

    }

    /***
     *  当前季度的开始时间和5个季度前的开始时间，即2012-01-1 00:00:00;2011-10-1 00:00:00
     *@return
     */
    public Map<String, String> getCurrentAndOldQuarterStartTime() {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int currentYear = c.get(Calendar.YEAR);
        int currentMonth = c.get(Calendar.MONTH) + 1;//"0"表示1月
        String now = null;
        String old = null;
        int oldYear = -1;
        int oldMonth = -1;
        try {
            if (currentMonth >= 1 && currentMonth <= 3) {
                c.set(Calendar.MONTH, 0);
//                oldYear=currentYear-3;
//                oldMonth=c.get(Calendar.MONTH)+9;
            } else if (currentMonth >= 4 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 3);
//                oldYear=currentYear-1;
//                oldMonth=c.get(Calendar.MONTH)+9;
            } else if (currentMonth >= 7 && currentMonth <= 9) {
                c.set(Calendar.MONTH, 6);
//                oldYear=currentYear-1;
//                oldMonth=c.get(Calendar.MONTH)+9;
            } else if (currentMonth >= 10 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 9);
//                oldYear=currentYear-1;
//                oldMonth=c.get(Calendar.MONTH)+9;
            }
            c.set(Calendar.DATE, 1);
            now = format1.format(c.getTime());
//            c.set(Calendar.YEAR,oldYear);
//            c.set(Calendar.MONTH,oldMonth);
            c.set(Calendar.YEAR, currentYear - 1);
            old = format1.format((c.getTime()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("now", now);
        dataMap.put("old", old);
        return dataMap;
    }

    /**
     * 同步惩处记录，按工号汇总员工的惩处记录
     *
     * @param periodStartDate
     * @param periodEndDate
     * @return
     */
    @Override
    public Map<String, String> syncPunishData(Date periodStartDate, Date periodEndDate) {
        EmpInfoDTO empDto = new EmpInfoDTO();
        empDto.setStartTime(DateUtils.dateFormat(periodStartDate, BusiEnumDefine.DATE_FORMAT_YYYY_MM_DD));
        empDto.setEndTime(DateUtils.dateFormat(periodEndDate, BusiEnumDefine.DATE_FORMAT_YYYY_MM_DD));
        Map<String, String> resultMap = new HashMap<>();
        String punishStr = dataCenterFeignClient.syncPunishRecord(JSONObject.toJSONString(empDto), commService.getPerformanceToken());
        Result<List<SyncEmpDTO>> punishListResult = JSON.parseObject(punishStr, new TypeReference<Result<List<SyncEmpDTO>>>() {
        });
        if (punishListResult == null) {
            return resultMap;
        }
        List<SyncEmpDTO> punishList = punishListResult.getData();
        if (punishList == null || punishList.size() == 0) {
            return resultMap;
        }
        for (SyncEmpDTO dto : punishList) {
            String itemType = dto.getItemType();//奖惩类别：奖励; 惩罚;
            if (!StringUtils.isEmpty(itemType) && itemType.equals("惩罚")) {
                String workerId = dto.getEmpCode();
                String rewardType = dto.getRewardType();//惩处的名称： 三级违规
                String rewardDate = dto.getRewardDate();//惩处的日期
                String rewardName = dto.getRewardName();//惩处
                StringBuilder sb = new StringBuilder();
                sb.append(rewardType).append("(").append(rewardDate).append(" ").append(rewardName).append(")");
                String punishString = resultMap.get(workerId);
                if (StringUtils.isEmpty(punishString)) {
                    resultMap.put(workerId, sb.toString());
                } else {
                    resultMap.put(workerId, punishString + "," + sb);
                }
            }
        }
        return resultMap;
    }

    //根据工号查询角色判断拥有的部门权限
    @Override
    public List<Integer> queryDeptForUser(String userId) {
        List<Integer> deptIdList = new ArrayList<>();
        List<SdDept> sdDepts = new ArrayList<>();
        SdUser sdUser = sdUserMapper.selectById(userId);
        if (sdUser != null) {
            /*String userRole = sdUser.getUserRole();
            String us = "";*/
            if(commService.getLoginUserRole().contains(String.valueOf(BusiEnumDefine.USER_ROLE_BP))
            ||commService.getLoginUserRole().contains(String.valueOf(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR))
            ||commService.getLoginUserRole().contains(String.valueOf(BusiEnumDefine.USER_ROLE_TEACHER_MANAGER))
            ||commService.getLoginUserRole().contains(String.valueOf(BusiEnumDefine.USER_ROLE_GBBZ))
            ){
                List<SdDept> sdDeptList = sdDeptMapper.selectList(new QueryWrapper<SdDept>().lambda()
                        .like(SdDept::getBpUserId,userId)
                        .or().like(SdDept::getContactorId,userId)
                        .or().like(SdDept::getGbbzId,userId)
                        .or().like(SdDept::getDeptManagerId,userId)
                );
                sdDepts.addAll(sdDeptList);
            }
          /*  for (String role : userRole.split(",")) {
                if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_BP || Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_TEACHER_MANAGER){
                    us = "bp_user_id";
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR){
                    us = "contactor_id";
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_GBBZ){
                    us = "gbbz_id";
                }
            }
            if(us.equals("")){
                return deptIdList;
            }else{
                List<SdDept> sdDepts1 = sdDeptMapper.selectList(new QueryWrapper<SdDept>().like(us, userId));
                sdDepts.addAll(sdDepts1);
//                deptIdList = sdDepts.stream().map(SdDept::getDeptId).collect(Collectors.toList());
            }*/
        }
        //部门主管
        if(commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_MANAGER)){
            SdAllWorker worker = commService.getAllWorkerDoFromLocalCache(userId);
            Integer directDeptId = worker.getDirectDeptId();
            List<SdDept> sdDepts2 = sdDeptMapper.selectList(new QueryWrapper<SdDept>()
                    .like("dept_code_chain",String.valueOf(directDeptId)));
            sdDepts.addAll(sdDepts2);
        }
        deptIdList = sdDepts.stream().distinct().map(SdDept::getDeptId).collect(Collectors.toList());
        return deptIdList;
    }

    @Override
    public PageInfo<TbTeacherAllowanceDTO> getTeacherAllowance(TbTeacherAllowanceDTO params, Integer currentPage, Integer pageSize) {
        Set<Integer> authDeptIds = judgeAuth();
        if (authDeptIds != null && authDeptIds.size() == 0) {
            return new PageInfo<>();
        }
        params.setAuthDeptIds(authDeptIds);
        Page<TbTeacherAllowanceDTO> page = PageHelper.startPage(currentPage, pageSize);
        List<TbTeacherAllowanceDTO> resList = queryTeacherAllowanceHandle(params);
        PageInfo<TbTeacherAllowanceDTO> tbTeacherAllowanceDTOPageInfo = page.toPageInfo();
        tbTeacherAllowanceDTOPageInfo.setList(resList);
        return tbTeacherAllowanceDTOPageInfo;
    }

    public Set<Integer> judgeAuth(){
        if (commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN)){
            return null;
        } else if (commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_TEACHER_MANAGER)) {
            return deptService.getAuthDeptIds(true, false, false, false);
        } else if (commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_BP)) {
            return deptService.getAuthDeptIds(true, false, false, false);
        } else if (commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR)) {
            return deptService.getAuthDeptIds(false, true, false, false);
        } else{
            return new HashSet<>();
        }
    }

    public List<TbTeacherAllowanceDTO> queryTeacherAllowanceHandle(TbTeacherAllowanceDTO params) {

        List<TbTeacherAllowanceDTO> teacherAllowanceList = teachScheduleMapper.selectWorkerTeacher(params);
        teacherAllowanceList.forEach(item -> {
            Date teachEndDate = item.getTeachEndDate();
            Date teachStartDate = item.getTeachStartDate();
//            实际相差月数
            int betweenMonthTrue = ((Long)DateUtil.betweenMonth(teachStartDate, teachEndDate, false)).intValue();
            //应相差月数
            int betweenMonth = ((Long)DateUtil.betweenMonth(teachStartDate, teachEndDate, true)).intValue();

            if (betweenMonthTrue < betweenMonth || betweenMonth == 0) {
                Calendar instance = Calendar.getInstance();
                instance.setTime(teachStartDate);
                instance.add(Calendar.MONTH,betweenMonthTrue);
                Date time = instance.getTime();
                long betweenDay = DateUtil.betweenDay(time, teachEndDate, true);
                if (betweenDay > 15) {
                    betweenMonthTrue ++;
                }
            }
            if(!StringUtils.isEmpty(item.getDataSrc())){
                if (!item.getDataSrc().contains("社") && betweenMonthTrue > 3) {
                    betweenMonthTrue = 3;
                }
            }

            item.setAllowanceMoney(betweenMonthTrue * allowanceMoney);
            if (item.getDeptNameChain() != null) {
                String[] split = item.getDeptNameChain().split("/");
                int length = split.length;
                if (length == 2) {
                    item.setDept1Name(split[1]);
                }else if (length == 3) {
                    item.setDept1Name(split[1]);
                    item.setDept2Name(split[2]);
                }else if (length == 4) {
                    item.setDept1Name(split[1]);
                    item.setDept2Name(split[2]);
                    item.setDept3Name(split[3]);
                }
                item.setDirectDeptName(split[length - 1]);
            }
            item.setWagesName("思想导师津贴");
            item.setCurrency("CNY");
        });
        return teacherAllowanceList;
    }

    @Override
    public void updateTeacherCertified(String teacherId) {
        //查询出本次调用的导师
        LambdaQueryWrapper<TbTeacher> queryWrapper = new QueryWrapper<TbTeacher>().lambda();
        queryWrapper.eq(TbTeacher::getCertifiedStatus, CertifiedStatusEnum.UNDER_CERTIFICATION.getCode());
        if (!StringUtils.isEmpty(teacherId)) {
            queryWrapper.eq(TbTeacher::getTeacherId, teacherId);
        }
        List<TbTeacher> tbTeacherList = list(queryWrapper);
        XxlJobLogger.log("共有{}名思想导师待认证", tbTeacherList.size());

        //调用大讲堂接口获取导师成功
        String token = "";
        if (tbTeacherList.size() > 0) {
            token = "Bearer " + userUtils.getToken(eosNemAccount, eosNemPassword);
        }
        for (TbTeacher teacher : tbTeacherList) {
            //调用接口
            String id = teacher.getTeacherId();
            String teacherName = teacher.getTeacherName();
            XxlJobLogger.log("思想导师{}认证开始", teacherName);
            String workerId = CommonUtil.GetEmpCodeToZero(id);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("courseId", courseId);
            jsonObject.put("empCode", workerId);
            XxlJobLogger.log("入参信息：",jsonObject);
            JSONObject teacherData = eosSyncDataClient.queryTeacherTraining(token, jsonObject.toJSONString());
            XxlJobLogger.log("接口返回成功：{}", teacherData);
            //存在成绩
            String code = teacherData.getString("code");
            JSONArray resArray = teacherData.getJSONArray("data");
            String emailTitle = "";
            String emailContent = "";

            if ("20216".equals(code) && !resArray.isEmpty()) {
                JSONObject object = resArray.getJSONObject(0);
                Date endDate = object.getDate("EndDate");
                Date beginDate = object.getDate("BegDate");
                Integer count = approvalRecordService.selectRecordByDate(id,
                        BusiEnumDefine.TEACHER_CERTIFICATION_APPROVAL, beginDate, endDate);
                if (count > 0) {
                    XxlJobLogger.log("查询到老数据");
                    Date createTime = teacher.getCreateTime();
                    Date date = DateUtils.dateAddDays(createTime, 14);
                    if (date.before(new Date())) {
                        teacher.setCertifiedTime(new Date());
                        teacher.setCertifiedStatus(CertifiedStatusEnum.TIMED_OUT.getCode());
                        XxlJobLogger.log("认证超时");
                        approvalRecordService.saveRecord(id, BusiEnumDefine.TEACHER_CERTIFICATION_APPROVAL, null, null, "认证超时", 2);
                        SdEmailTemplate emailTemplate = emailTemplateService.getById("teacher_certification_timeout");
                        if (emailTemplate == null) {
                            XxlJobLogger.log("找不到邮件模板，邮件发送取消");
                            continue;
                        }
                        emailTitle = emailTemplate.getEmailTemplateTitle();
                        emailContent = emailTemplate.getEmailTemplateContent();
//                        {导师姓名}，您好：
//                          思想导师赋能认证需在7天内完成，即截止日期为{截止日期}，您本次的认证超时，认证通道已关闭，请了解，谢谢。
//                          （如需重新认证，请联系部门接口人{部门接口人}重新发起）
                        Date week = DateUtils.dateAddDays(createTime, 7);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String weekStr = dateFormat.format(week);
                        String contactorName = getContactorName(id);
                        emailContent = emailContent.replace("{导师姓名}", teacherName).replace("{截止日期}", weekStr)
                                .replace("{部门接口人}", contactorName);
                    }
                } else {
                    int score = object.getIntValue("CourseGrades");
                    XxlJobLogger.log("思想导师成绩：{}", score);
                    //分数通过
                    teacher.setCertifiedTime(new Date());
                    if (score >= 80) {
                        teacher.setCertifiedStatus(CertifiedStatusEnum.PASSED.getCode());
                        approvalRecordService.saveRecord(id, BusiEnumDefine.TEACHER_CERTIFICATION_APPROVAL, null, null,
                                "认证成功", 1, String.valueOf(score), beginDate, endDate);
                        SdEmailTemplate emailTemplate = emailTemplateService.getById("teacher_certification_success");
                        if (emailTemplate == null) {
                            XxlJobLogger.log("找不到邮件模板，邮件发送取消");
                            continue;
                        }
                        emailTitle = emailTemplate.getEmailTemplateTitle();
                        emailContent = emailTemplate.getEmailTemplateContent();
//{导师姓名}，您好：
//恭喜您以{认证成绩}分的成绩通过思想导师赋能认证，成为新华三思想导师中的一员！从今天起您，您将可以正式带教部门新员工。新员工试用期期间通过新员工系统线上管理，未来您可登陆系统查看您带教新员工每月考核情况及您的导师津贴发放情况，谢谢！
//
//      点击进入新员工系统链接：XXXXX
                        emailContent = emailContent.replace("{导师姓名}", teacherName).replace("{认证成绩}", String.valueOf(score));

                    } else {
                        teacher.setCertifiedStatus(CertifiedStatusEnum.FAIL.getCode());
                        approvalRecordService.saveRecord(id, BusiEnumDefine.TEACHER_CERTIFICATION_APPROVAL, null, null,
                                "认证失败", 2, String.valueOf(score), beginDate, endDate);
                        SdEmailTemplate emailTemplate = emailTemplateService.getById("teacher_certification_fail");
                        if (emailTemplate == null) {
                            XxlJobLogger.log("找不到邮件模板，邮件发送取消");
                            continue;
                        }
                        emailTitle = emailTemplate.getEmailTemplateTitle();
                        emailContent = emailTemplate.getEmailTemplateContent();
//                        {导师姓名}，您好：
//                              您本的思想导师赋能认证成绩为{认证成绩}分，未达到80分数线，很遗憾通知您本次认证未通过，谢谢。
//                              （如需重新认证，请联系部门接口人{部门接口人}重新发起）
                        String contactorName = getContactorName(id);
                        emailContent = emailContent.replace("{导师姓名}", teacherName).replace("{认证成绩}", String.valueOf(score))
                                .replace("{部门接口人}", contactorName);

                    }
                }
            } else {
                //没有数据
                XxlJobLogger.log("查询不到思想导师成绩");
                Date createTime = teacher.getCreateTime();
                Date date = DateUtils.dateAddDays(createTime, 14);
                if (date.before(new Date())) {
                    teacher.setCertifiedTime(new Date());
                    teacher.setCertifiedStatus(CertifiedStatusEnum.TIMED_OUT.getCode());
                    XxlJobLogger.log("认证超时");
                    approvalRecordService.saveRecord(id, BusiEnumDefine.TEACHER_CERTIFICATION_APPROVAL, null, null, "认证超时", 2);
                    SdEmailTemplate emailTemplate = emailTemplateService.getById("teacher_certification_timeout");
                    if (emailTemplate == null) {
                        XxlJobLogger.log("找不到邮件模板，邮件发送取消");
                        continue;
                    }
                    emailTitle = emailTemplate.getEmailTemplateTitle();
                    emailContent = emailTemplate.getEmailTemplateContent();
//                        {导师姓名}，您好：
//                          思想导师赋能认证需在7天内完成，即截止日期为{截止日期}，您本次的认证超时，认证通道已关闭，请了解，谢谢。
//                          （如需重新认证，请联系部门接口人{部门接口人}重新发起）
                    Date week = DateUtils.dateAddDays(createTime, 7);
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String weekStr = dateFormat.format(week);
                    String contactorName = getContactorName(id);
                    emailContent = emailContent.replace("{导师姓名}", teacherName).replace("{截止日期}", weekStr)
                            .replace("{部门接口人}", contactorName);
                }
            }
            XxlJobLogger.log("思想导师{}认证结束", teacherName);

            if (!StringUtils.isEmpty(emailTitle)) {
                XxlJobLogger.log("发送邮件提醒思想导师{}", teacherName);
                SdAllWorker workerCache = commService.getAllWorkerDoFromLocalCache(id);
                if (workerCache != null) {
                    String copyEmail = getContactorAndManageEmail(workerCache);
                    SdNoticeRecord noticeRecord = noticeRecordService.createEmailNoticeRecord("-1", id, teacherName,
                            workerCache.getEmail(), emailTitle, emailContent, copyEmail);
                    XxlJobLogger.log("邮件创建成功：{}", noticeRecord);
                    sendMessage.sendMessage(Collections.singletonList(noticeRecord));
                }
            }
        }
        updateBatchById(tbTeacherList);
        XxlJobLogger.log("更新完成");
    }

    private String getContactorName(String teacherId) {
        SdAllWorker teacher = commService.getAllWorkerDoFromLocalCache(teacherId);
        if (teacher == null) {
            return "";
        }
        Integer directDeptId = teacher.getDirectDeptId();
        SdDept sdDept = deptService.getById(directDeptId);
        if (sdDept == null) {
            XxlJobLogger.log("找不到部门:{}", directDeptId);
            return "";
        }
        String contactor = deptService.getContactorByDeptNameChain(sdDept.getDeptNameChain(), teacher.getWorkCity());
        SdAllWorker contactorWorker = commService.getAllWorkerDoFromLocalCache(contactor);
        if (contactorWorker == null) {
            return "";
        }
        return contactorWorker.getWorkerName() + "/" + contactorWorker.getWorkerId();
    }

    private String getContactorAndManageEmail(SdAllWorker workerCache) {
        Integer directDeptId = workerCache.getDirectDeptId();
        SdDept sdDept = deptService.getById(directDeptId);
        if (sdDept == null) {
            return "";
        }
        String deptManagerId = sdDept.getDeptManagerId();
        SdAllWorker manage = commService.getAllWorkerDoFromLocalCache(deptManagerId);
        String email = manage == null ? "" : manage.getEmail();
        String contactor = deptService.getContactorByDeptNameChain(sdDept.getDeptNameChain(), workerCache.getWorkCity());
        SdAllWorker contactorWorker = commService.getAllWorkerDoFromLocalCache(contactor);
        String contactorEmail = contactorWorker == null ? "" : contactorWorker.getEmail();
        return Stream.of(email, contactorEmail).filter(StringUtils::hasText).collect(Collectors.joining(","));
    }

    //检测导师绩效，同时更新是否满足条件：返回所有不满足的导师
    public List<TbTeacherDTO> changeTeacherResult(List<TbTeacherDTO> tbTeacherDTOS) {
//        List<TbTeacher> list = tbTeacherMapper.selectList(new QueryWrapper<>());
//        List<TbTeacherDTO> tbTeacherDTOS = JSONArray.parseArray(JSONArray.toJSONString(list), TbTeacherDTO.class);
        List<TbTeacherDTO> resultChangeList = new ArrayList<>();

        String checkResultMsg = "";
        for (TbTeacherDTO tbTeacherDTO : tbTeacherDTOS) {
            int checkResultFlag = 1;//默认满足导师任职条件

//            //判断司龄
//            SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(tbTeacherDTO.getTeacherId());
//            if(sdAllWorker==null){
//                continue;
//            }else {
//                if(sdAllWorker.getJoinDate()==null){
//                    continue;
//                }
//            }
//            Date jionDate = sdAllWorker.getJoinDate();
//            int year = com.h3c.nem.utils.DateUtil.getAge(jionDate);
//            if(year>=1){
//            }else{
//                checkResultFlag = 2;
//                checkResultMsg = "司龄不满足导师任职条件";
//            }
            if (checkResultFlag == 1) {
                int countC = 0;
                int countD = 0;
                if (!StringUtils.isEmpty(tbTeacherDTO.getLast4kpi())) {
                    String[] arr = tbTeacherDTO.getLast4kpi().split(";");
                    for (int i = 0; i < 4; i++) {
                        if (arr.length > i) {
                            String str = arr[i].split(":")[1];
                            if (Objects.equals(str, "C")) {
                                countC++;
                            }
                            if (Objects.equals(str, "D")) {
                                countD++;
                            }
                        }
                    }
                }
                if (countC >= 3 || countD >= 2 || countC + countD >= 3) {//绩效不符合，满足条件标志为满足
                    checkResultFlag = 2;
                    checkResultMsg = "绩效不满足导师任职条件";
                }
            }

            //判断完绩效，仍然满足，再判断文化
            if (checkResultFlag == 1) {
                int count3 = 0;
                int count4 = 0;
                if (!StringUtils.isEmpty(tbTeacherDTO.getLast4culture())) {
                    String[] arr = tbTeacherDTO.getLast4culture().split(";");
                    for (int i = 0; i < 4; i++) {
                        if (arr.length > i) {
                            String str = arr[i].split(":")[1];
                            if (Objects.equals(str, "3级")) {
                                count3++;
                            }
                            if (Objects.equals(str, "4级")) {
                                count4++;
                            }
                        }
                    }
                }
                if (count3 >= 3 || count4 >= 2 || count3 + count4 >= 3) {
                    checkResultFlag = 2;
                    checkResultMsg = "领航者文化不满足导师任职条件";
                }
            }
            //判定惩处
            if(checkResultFlag == 1){
                int count = 0;
                if(!StringUtils.isEmpty(tbTeacherDTO.getLastPunishRecord())){
                    String[] arr = tbTeacherDTO.getLastPunishRecord().split(";");
                    for (String s : arr) {
                        if(s.contains("二级违规")||s.contains("一级违规")){
                            count++;
                        }
                    }
                }
                if(count>0){
                    checkResultFlag = 2;
                    checkResultMsg = "惩处不满足导师任职条件";
                }
            }

            tbTeacherDTO.setCheckResultFlag(checkResultFlag);
            tbTeacherDTO.setCheckResultMsg(checkResultMsg);

            //判定后不满足条件的导师
            if(checkResultFlag == 2){
                resultChangeList.add(tbTeacherDTO);
            }
            if(tbTeacherMapper.selectCount(new QueryWrapper<TbTeacher>().eq("teacher_id", tbTeacherDTO.getTeacherId()))>0){
                if(checkResultFlag == 2){
                    //系统判定后不符合资质的直接移除导师库
                    tbTeacherMapper.deleteById(tbTeacherDTO.getTeacherId());
                    //todo 邮件
                    /*UpdateWrapper<TbTeacher> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("teacher_id", tbTeacherDTO.getTeacherId())
                            .ne("check_result_flag", 2)
                            .set("check_result_flag", 2)
                            .set("certified_status",BusiEnumDefine.TEACHER_CERTIFIED_STATUS_CANCEL);//更新不满足条件标志,同时取消资格
                    tbTeacherMapper.update(null, updateWrapper);*/
                    SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(tbTeacherDTO.getTeacherId());

                    if(sdAllWorker!=null){
                        List<String> copyToList = getTeacherManager(sdAllWorker);
                        SdEmailTemplate emailTemplate = emailTemplateService.getById("TEACHER_CANCEL_AUTO");
                        String templateContent = emailTemplate.getEmailTemplateContent();
                        String copyTo = "";
                        if(!CollectionUtils.isEmpty(copyToList)){
                            String copyToId = copyToList.get(0);
                            SdAllWorker teacherManager = commService.getAllWorkerDoFromLocalCache(copyToId);
                            if(teacherManager!=null){
                                copyTo = teacherManager.getEmail();
                                templateContent = templateContent .replace("{咨询人}",teacherManager.getWorkerName()+"/"+teacherManager.getWorkerId());
                            }
                        }
                        String templateTitle = emailTemplate.getEmailTemplateTitle();
                        templateContent = templateContent.replace("{原因}", tbTeacherDTO.getCheckResultMsg());
                        SdNoticeRecord noticeRecord = iSdNoticeRecordService.createEmailNoticeRecord("-1", tbTeacherDTO.getTeacherId(), tbTeacherDTO.getTeacherName(), sdAllWorker.getEmail(), templateTitle, templateContent, copyTo);
                        asyncSendMessage.sendMessage(Collections.singletonList(noticeRecord));
                    }
                }else{
                    //取消资格的不自动恢复
/*                    UpdateWrapper<TbTeacher> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("teacher_id", tbTeacherDTO.getTeacherId())
                            .ne("check_result_flag", 1).set("check_result_flag", 1);//更新满足条件标志
                    tbTeacherMapper.update(null, updateWrapper);*/
                }
            }
        }
        return resultChangeList;
    }

    /**
     * 找到导师对应的导师管理员
     * */
    public List<String>  getTeacherManager(SdAllWorker sdAllWorker){
       /* List<SdUser> sdUserList = sdUserMapper.selectList(new QueryWrapper<SdUser>().lambda()
                .eq(SdUser::getUserRole,BusiEnumDefine.USER_ROLE_TEACHER_MANAGER)
                .or().eq(SdUser::getTeacherFlag,1));
        List<String> userIds = sdUserList.stream().map(SdUser::getUserId).collect(Collectors.toList());*/
        Integer deptId = sdAllWorker.getDirectDeptId();

        SdDept sdDept = sdDeptMapper.selectById(deptId);
        List<String> workerIds = new ArrayList<>();
        String bpIds = sdDept.getBpUserId();
        if(!StringUtils.isEmpty(bpIds)){
            workerIds.addAll(Arrays.asList(bpIds.split(",")));
        }
        String conIds = sdDept.getContactorId();
        if(!StringUtils.isEmpty(conIds)){
            workerIds.addAll(Arrays.asList(bpIds.split(",")));
        }
        List<SdUser> sdUserList = sdUserMapper.selectList(new QueryWrapper<SdUser>().lambda()
                .in(SdUser::getUserId,workerIds));
        List<String> idList = new ArrayList<>();
        for (SdUser sdUser : sdUserList) {
            if(sdUser.getUserRole().contains(String.valueOf(BusiEnumDefine.USER_ROLE_TEACHER_MANAGER))||sdUser.getTeacherFlag()==1){
                idList.add(sdUser.getUserId());
            }
        }
//        List<String> idList = userIds.stream().filter(workerIds::contains).collect(Collectors.toList());
        return idList;
    }


    @Override
    public List<TbTeacherDTO>  checkTeacherFlag(List<TbTeacherDTO> tbTeacherDTOS){
        for (TbTeacherDTO tbTeacherDTO : tbTeacherDTOS) {
            int checkResultFlag = 1;//默认满足导师任职条件
            int countC = 0;
            int countD = 0;
            //判断司龄
            SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(tbTeacherDTO.getTeacherId());
//            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//如2016-08-10 20:40
            Date jionDate = sdAllWorker.getJoinDate();
            int year = com.h3c.nem.utils.DateUtil.getAge(jionDate);
            if(year>=1){
            }else{
                checkResultFlag = 2;
            }
            //判断完司龄后判断季度绩效
            if(checkResultFlag==1){
                if (!StringUtils.isEmpty(tbTeacherDTO.getLast4kpi())) {
                    String[] arr = tbTeacherDTO.getLast4kpi().split(";");
                    for (int i = 0; i < 4; i++) {
                        if (arr.length > i) {
                            String str = arr[i].split(":")[1];
                            if (Objects.equals(str, "C")) {
                                countC++;
                            }
                            if (Objects.equals(str, "D")) {
                                countD++;
                            }
                        }
                    }
                }
                if (countC >= 3 || countD >= 2 || countC + countD >= 3) {//绩效不符合，满足条件标志为满足
                    checkResultFlag = 2;
                }
            }
            //判断完绩效，仍然满足，再判断文化
            if (checkResultFlag == 1) {
                int count3 = 0;
                int count4 = 0;
                if (!StringUtils.isEmpty(tbTeacherDTO.getLast4culture())) {
                    String[] arr = tbTeacherDTO.getLast4culture().split(";");
                    for (int i = 0; i < 4; i++) {
                        if (arr.length > i) {
                            String str = arr[i].split(":")[1];
                            if (Objects.equals(str, "3级")) {
                                count3++;
                            }
                            if (Objects.equals(str, "4级")) {
                                count4++;
                            }
                        }
                    }
                }
                if (count3 >= 3 || count4 >= 2 || count3 + count4 >= 3) {
                    checkResultFlag = 2;
                }
            }
            //判定惩处
            if(checkResultFlag == 1){
                int count = 0;
                if(!StringUtils.isEmpty(tbTeacherDTO.getLastPunishRecord())){
                    String[] arr = tbTeacherDTO.getLastPunishRecord().split(";");
                    for (String s : arr) {
                        if(s.contains("二级违规")){
                            count++;
                        }
                    }
                }
                if(count>0){
                    checkResultFlag = 2;
                }
            }
            tbTeacherDTO.setCheckResultFlag(checkResultFlag);
        }
        return tbTeacherDTOS;
    }


    //认证状态为认证通过，但绩效文化又不满足任职条件的发送邮件；
    @Override
    public void sendEmailByStatus() {

        List<TbTeacher> tbTeacherList = tbTeacherMapper.selectList(new QueryWrapper<TbTeacher>().eq("check_result_flag", 2)
                .eq("certified_status", 3));
        List<TbTeacherDTO> teacherList = JSONArray.parseArray(JSONArray.toJSONString(tbTeacherList), TbTeacherDTO.class);
//        Map<String, List<TbTeacherDTO>> teacherMap = teacherList.stream().collect(Collectors.groupingBy(TbTeacherDTO::getTeacherId));

        List<String> sendIdList = new ArrayList<>();
        Map<String, List<TbTeacherDTO>> sendMap = new HashMap<>();

        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        for (TbTeacherDTO tbTeacherDTO : teacherList) {
            SdDept directDept = (SdDept) dataCacheMap.get("dept-" + tbTeacherDTO.getDirectDeptId());
            String bpUserId = directDept.getBpUserId();
            String contactorId = directDept.getContactorId();

            for (String s : bpUserId.split(",")) {
                SdUser sdUser = sdUserMapper.selectOne(new QueryWrapper<SdUser>().eq("user_id", s));
                if (!ObjectUtils.isEmpty(sdUser) && !StringUtils.isEmpty(sdUser.getTeacherFlag()) && sdUser.getTeacherFlag() == 1) {
                    sendIdList.add(s);
                    List<TbTeacherDTO> tbTeacherDTOS = new ArrayList<>();
                    if(sendMap.get(s)!=null){
                        tbTeacherDTOS.addAll(sendMap.get(s));
                    }
                    tbTeacherDTOS.add(tbTeacherDTO);
                    sendMap.put(s, tbTeacherDTOS);
                }

            }
            for (String s : contactorId.split(",")) {
                SdUser sdUser = sdUserMapper.selectOne(new QueryWrapper<SdUser>().eq("user_id", s));
                if (!ObjectUtils.isEmpty(sdUser) && !StringUtils.isEmpty(sdUser.getTeacherFlag()) && sdUser.getTeacherFlag() == 1) {
                    sendIdList.add(s);
                    List<TbTeacherDTO> tbTeacherDTOS = sendMap.get(s);
                    if(sendMap.get(s)!=null){
                        tbTeacherDTOS.addAll(sendMap.get(s));
                    }
                    tbTeacherDTOS.add(tbTeacherDTO);
                    sendMap.put(s, tbTeacherDTOS);
                }

            }
        }

        List<String> sendIdList1 = sendIdList.stream().distinct().collect(Collectors.toList());
        List<SdNoticeRecord> sendList = new ArrayList<>();
        SdEmailTemplate emailTemplate = emailTemplateService.getById(BusiEnumDefine.TEACHER_CHANGE);
        String content = emailTemplate.getEmailTemplateContent();
        if (!sendIdList1.isEmpty()) {
            for (String sendId : sendIdList1) {
                StringBuilder text = new StringBuilder();
                text.append("{");
                List<TbTeacherDTO> tbTeacherDTOS = sendMap.get(sendId);
                for (TbTeacherDTO tbTeacherDTO : tbTeacherDTOS) {
                    text.append(tbTeacherDTO.getTeacherName()).append("/").append(tbTeacherDTO.getTeacherId()).append(",");
                }

                SdAllWorker sendWorker = (SdAllWorker) dataCacheMap.get("allworker-" + sendId);
                if (sendWorker != null) {
                    SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
                    sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
                    sdNoticeRecord.setCopyToEmail("");
                    sdNoticeRecord.setTargetEmail(sendWorker.getEmail());
//                sdNoticeRecord.setNoticeContent(emailTemplate.getEmailTemplateContent());
                    sdNoticeRecord.setNoticeContent(content.replace("{姓名/工号}", text.substring(0,text.length()-1)+"}"));
                    sdNoticeRecord.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
                    sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
                    sdNoticeRecord.setTargetName(sendWorker.getWorkerName());
                    sdNoticeRecord.setTargetId(sendWorker.getWorkerId());
                    sdNoticeRecord.setCreateTime(new Date());
                    sendList.add(sdNoticeRecord);
                }
            }
        }
        commService.sendMessage(sendList);
    }

    /**
     * 部门主管自动进入导师库
     */
    @Override
    public void setTeacherCertForDeptManager(){
        List<SdDept> deptList = sdDeptMapper.selectList(new QueryWrapper<>());
        List<String> managerIdList = deptList.stream().map(SdDept::getDeptManagerId).collect(Collectors.toList());
        HashSet<String> idSet = new HashSet<String>();
        for (String s : managerIdList) {
            idSet.addAll(Arrays.asList(s.split(",")));
        }
        List<TbTeacher> tbTeacherList=new ArrayList<>();
        for (String s : idSet) {
            TbTeacher tbTeacher = new TbTeacher();
            SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(s);
            if(ObjectUtils.isEmpty(sdAllWorker)){
                continue;
            }
            SdDept sdDept = commService.getDept(sdAllWorker.getDirectDeptId());
            if(ObjectUtils.isEmpty(sdDept)){
                continue;
            }
            tbTeacher.setTeacherId(s);
            tbTeacher.setTeacherName(sdAllWorker.getWorkerName());
            tbTeacher.setDirectDeptId(sdAllWorker.getDirectDeptId());
            tbTeacher.setDeptNameChain(sdDept.getDeptNameChain());
            tbTeacher.setDeptCodeChain(sdDept.getDeptCodeChain());
            tbTeacher.setCertifiedStatus(3);
            tbTeacher.setCertifiedTime(new Date());
            tbTeacherList.add(tbTeacher);
        }
        saveOrUpdateBatch(tbTeacherList);
    }
}

